Chapter 16: TodoDataService - Connecting to the
Backend
To retrieve the list of todos from the database, we will need to connect to our backend server. We will create a
service class for that. A service is a class with a well-defined specific function your app needs. In our case, our
service is responsible for talking to the backend to get and save todo data. Service classes provide their functionality
to be consumed by components. We will cover components in the next few chapters.
Under src, create a new folder called services. In it, create a new file todos.js with the following code:
Add Code
import axios from 'axios';
class TodoDataService{
getAll(token){
axios.defaults.headers.common["Authorization"] = "Token " + token;
return axios.get('http://localhost:8000/api/todos/');[DCB7]
}
createTodo(data, token){
axios.defaults.headers.common["Authorization"] = "Token " + token;
return axios.post("http://localhost:8000/api/todos/", data);
}
updateTodo(id, data, token){
axios.defaults.headers.common["Authorization"] = "Token " + token;
return axios.put(`http://localhost:8000/api/todos/${id}`, data);
}
deleteTodo(id, token){
axios.defaults.headers.common["Authorization"] = "Token " + token;
return axios.delete(`http://localhost:8000/api/todos/${id}`);
}
completeTodo(id, token){
axios.defaults.headers.common["Authorization"] = "Token " + token;
return axios.put(`http://localhost:8000/api/todos/${id}/complete`);
}
login(data){
return axios.post("http://localhost:8000/api/login/", data);
}
signup(data){
return axios.post("http://localhost:8000/api/signup/", data);
}
}
export default new TodoDataService();
Code Explanation
Analyze Code
import axios from 'axios';
We use a library called axios for sending get, post, put and delete requests. Let’s first install axios, go to the
‘frontend’ folder, and in Terminal, run:
Execute in Terminal
npm install axios
The class TodoDataService contains functions which make the API calls to the backend endpoints we implemented
earlier and return the results.
Analyze Code
getAll(token){
axios.defaults.headers.common["Authorization"] = "Token " + token;
return axios.get('http://localhost:8000/api/todos/');
}